package com.example.sneakerappforme1105.orderFragment;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.sneakerappforme1105.DTO.OrderPostData;
import com.example.sneakerappforme1105.DataProvider;
import com.example.sneakerappforme1105.MainApplication;
import com.example.sneakerappforme1105.R;
import com.example.sneakerappforme1105.adapter.OrderAdapter;
import com.example.sneakerappforme1105.bean.Goods;
import com.example.sneakerappforme1105.bean.Order;
import com.example.sneakerappforme1105.bean.OrderItem;
import com.example.sneakerappforme1105.constant.NetConst;
import com.example.sneakerappforme1105.dao.OrderDao;
import com.example.sneakerappforme1105.dao.OrderItemDao;
import com.example.sneakerappforme1105.util.ToastUtil;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class PaidFragment extends Fragment {
    String TAG = "PaidFragment";
    protected View mView;
    protected AppCompatActivity mActivity;
    private RecyclerView rv_paid;
    private Long mUserId;   // 得传入订单
    private HashMap<Long, Goods> mGoodsMap = new HashMap<>(); // long 是info.goodsId作为外键
    private List<Order> mList = new ArrayList<>();
    private HashMap<Long, List<OrderItem>> map = new HashMap<>();// 订单id->所有的订单项
    private OrderDao orderDao;
    private OrderItemDao orderItemDao;
    private OrderAdapter orderAdapter;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        DataProvider dataProvider = (DataProvider) getActivity();   // 用来得到 所挂载活动的成员变量
        mView = inflater.inflate(R.layout.fragment_paid, container, false);
        mActivity = (AppCompatActivity) getActivity();
        orderDao = MainApplication.getInstance().getAppDatabase().orderDao();
        orderItemDao = MainApplication.getInstance().getAppDatabase().orderItemDao();
        rv_paid = mView.findViewById(R.id.rv_paid);
        if(dataProvider!=null){

            mUserId = dataProvider.getUserId();
            mGoodsMap = dataProvider.getGoodsMap();

        }




        Log.d(TAG,"待发货订单数为"+mList.size());
        orderAdapter = new OrderAdapter(mActivity,mList,map,mGoodsMap);
        LinearLayoutManager llm = new LinearLayoutManager(mActivity);
        rv_paid.setLayoutManager(llm);
        rv_paid.setAdapter(orderAdapter);

        orderAdapter.setDeleteListener(new OrderAdapter.OnDeleteListener() {
            @Override
            public void delete(View view, int position) {
                // 获取当前订单对象
                Order order = mList.get(position);
                long orderId = order.getOrderId();

                // 创建对话框
                AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
                builder.setTitle("删除订单")
                        .setMessage("确定要删除该订单吗？")
                        .setPositiveButton("确定", (dialog, which) -> {
                            // 点击确定后发送删除请求
                            deleteOrder(orderId, position);
                        })
                        .setNegativeButton("取消", (dialog, which) -> {
                            // 点击取消，关闭对话框
                            dialog.dismiss();
                        })
                        .show();
            }
        });

        fetchAllOrders(mUserId);
        return mView;
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG,"片段重启");
        fetchAllOrders(mUserId);    // 重新获得订单数据
    }

    private void fetchAllOrders(Long mUserId) {
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(NetConst.HTTP_PREFIX+"order/"+mUserId+"?status=paid")  // pathvariable
                .get()
                .build();


        client.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                System.out.println("请求订单错误！");
                mActivity.runOnUiThread(()->{
                    mList.clear();
                    map.clear();
                    // 从本地数据库加载订单
                    List<Order> localOrders = orderDao.queryAllOrderByUserId(mUserId);
                    for (Order order : localOrders) {
                        mList.add(order);
                        List<OrderItem> orderItems = orderItemDao.getOrderItemsByOrderId(order.getOrderId());
                        map.put(order.getOrderId(), orderItems);  // 从本地数据库加载关联的订单项
                    }
                    orderAdapter.notifyDataSetChanged();
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    String responseData = response.body().string();

                    Gson gson = new Gson();


                    JsonObject jsonObject = gson.fromJson(responseData, JsonObject.class);


                    JsonArray dataArray = jsonObject.getAsJsonArray("data");

                    Type orderType = new TypeToken<List<OrderPostData>>() {}.getType();
                    List<OrderPostData> orderPostDataList = gson.fromJson(dataArray, orderType); // 得到所有的订单以及订单项
                    int ordersize = orderPostDataList.size();
                    mList.clear();  // 清除之前的数据
                    map.clear();    // 清除之前的数据
                    int id = 0;
                    for (OrderPostData orderPostData : orderPostDataList) {
                        Order order = orderPostData.getOrder();
                        List<OrderItem> orderItems = orderPostData.getOrderItems();
                        if(id!=ordersize-1) {
                            mList.add(order);   // 当前该用户的所有订单
                        }else{
                            mList.add(0,order); // 将最后一个订单插入到第一个位置
                        }
                        map.put(order.getOrderId(), orderItems);    // 订单关联的订单项
                    }

                    // 更新 UI
                    mActivity.runOnUiThread(() -> {
                        orderAdapter.notifyDataSetChanged();
                        // 滚动到顶部
                        if (!mList.isEmpty()) {
                            rv_paid.scrollToPosition(0); // 滚动到最新订单
                        }

                    });


                }
            }


        });

    }


    private void deleteOrder(long orderId, int position) {
        OkHttpClient client = new OkHttpClient();


        String url = NetConst.HTTP_PREFIX+"order/" + orderId;

        Request request = new Request.Builder()
                .url(url)
                .delete()
                .build();


        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                // 请求失败
                Log.e("DeleteOrder", "删除订单失败：" + e.getMessage());
                mActivity.runOnUiThread(() -> ToastUtil.show(mActivity, "删除订单失败，请重试"));
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    // 删除成功，从列表中移除
                    mActivity.runOnUiThread(() -> {
                        mList.remove(position); // 移除订单
                        orderAdapter.notifyItemRemoved(position); // 刷新 RecyclerView
                        ToastUtil.show(mActivity, "删除订单成功");
                    });
                } else {
                    // 请求失败，显示错误信息
                    Log.e("DeleteOrder", "删除订单失败：" + response.message());
                    mActivity.runOnUiThread(() ->
                            ToastUtil.show(mActivity, "删除订单失败，请重试")
                    );
                }
            }
        });
    }

}
